import torch
import torch.nn as nn


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, in_channels, out_channels, stride=1, downsample=None,
                 Conv2d=nn.Conv2d, **kwargs):
        super(BasicBlock, self).__init__()
        
        self.conv1 = Conv2d(in_channels, out_channels, kernel_size=3, stride=stride,
                                padding=1, bias=False, **kwargs)
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = Conv2d(out_channels, out_channels, kernel_size=3, stride=1,
                                padding=1, bias=False, **kwargs)
        self.bn2 = nn.BatchNorm2d(out_channels)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class BottleNeck(nn.Module):
    expansion = 4

    def __init__(self, in_channels, out_channels, stride=1, downsample=None,
                 Conv2d=nn.Conv2d, **kwargs):
        super(BottleNeck, self).__init__()

        self.conv1 = Conv2d(in_channels, out_channels, kernel_size=1, bias=False, **kwargs)
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.conv2 = Conv2d(out_channels, out_channels, kernel_size=3, stride=stride,
                                padding=1, bias=False, **kwargs)
        self.bn2 = nn.BatchNorm2d(out_channels)
        self.conv3 = Conv2d(out_channels, out_channels * self.expansion, 
                            kernel_size=1, bias=False, **kwargs)
        self.bn3 = nn.BatchNorm2d(out_channels * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class ResNet(nn.Module):
    
    def __init__(self, block, layers, num_classes=1000,
                 dataset='imagenet', Conv2d=nn.Conv2d, Linear=nn.Linear, **kwargs):
        super(ResNet, self).__init__()

        self.dataset = dataset
        if dataset == 'imagenet':
            self.in_channels = 64
            self.conv1 = Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                                    bias=False, **kwargs)
            self.bn1 = nn.BatchNorm2d(64)
            self.relu = nn.ReLU(inplace=True)
            self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
            self.layer1 = self._make_layer(block, 64, layers[0], Conv2d=Conv2d, **kwargs)
            self.layer2 = self._make_layer(block, 128, layers[1], stride=2, Conv2d=Conv2d, **kwargs)
            self.layer3 = self._make_layer(block, 256, layers[2], stride=2, Conv2d=Conv2d, **kwargs)
            self.layer4 = self._make_layer(block, 512, layers[3], stride=2, Conv2d=Conv2d, **kwargs)
            self.avgpool = nn.AvgPool2d(7, stride=1)
            self.fc = Linear(512 * block.expansion, num_classes)
        elif dataset == 'cifar10':
            self.in_channels = 16
            self.conv1 = Conv2d(3, 16, kernel_size=3, stride=1, padding=1,
                                    bias=False, **kwargs)
            self.bn1 = nn.BatchNorm2d(16)
            self.relu = nn.ReLU(inplace=True)
            self.layer1 = self._make_layer(block, 16, layers[0], Conv2d=Conv2d, **kwargs)
            self.layer2 = self._make_layer(block, 32, layers[1], stride=2, Conv2d=Conv2d, **kwargs)
            self.layer3 = self._make_layer(block, 64, layers[2], stride=2, Conv2d=Conv2d, **kwargs)
            self.avgpool = nn.AvgPool2d(8, stride=1)
            self.flatten = nn.Flatten(1)
            self.fc = Linear(64 * block.expansion, num_classes)
        else:
            raise ValueError('dataset should be imagenet or cifar10')

        for m in self.modules():
            if isinstance(m, nn.Conv2d): # only init nn.Conv2d
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, out_channels, blocks, stride=1,
                    Conv2d=nn.Conv2d, **kwargs):
        downsample = None
        if stride != 1 or self.in_channels != out_channels * block.expansion:
            downsample = nn.Sequential(
                Conv2d(self.in_channels, out_channels * block.expansion,
                            kernel_size=1, stride=stride, bias=False, **kwargs),
                nn.BatchNorm2d(out_channels * block.expansion),
            )

        layers = []
        layers.append(block(self.in_channels, out_channels, stride, downsample,
                            Conv2d=Conv2d, **kwargs))
        self.in_channels = out_channels * block.expansion
        for _ in range(1, blocks):
            layers.append(block(self.in_channels, out_channels, Conv2d=Conv2d, **kwargs))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        if self.dataset == 'imagenet':
            x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        if self.dataset == 'imagenet':
            x = self.layer4(x)

        x = self.avgpool(x)
        # x = torch.flatten(x, 1)
        x = self.flatten(x)
        x = self.fc(x)

        return x

# imagenet
def resnet18(**kwargs):
    return ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)

def resnet34(**kwargs):
    return ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)

def resnet50(**kwargs):
    return ResNet(BottleNeck, [3, 4, 6, 3], **kwargs)

def resnet101(**kwargs):
    return ResNet(BottleNeck, [3, 4, 23, 3], **kwargs)

def resnet152(**kwargs):
    return ResNet(BottleNeck, [3, 8, 36, 3], **kwargs)


# cifar10
def resnet20(**kwargs):
    return ResNet(BasicBlock, [3, 3, 3], num_classes=10, dataset='cifar10', **kwargs)

def resnet32(**kwargs):
    return ResNet(BasicBlock, [5, 5, 5], num_classes=10, dataset='cifar10', **kwargs)

def resnet44(**kwargs):
    return ResNet(BasicBlock, [7, 7, 7], num_classes=10, dataset='cifar10', **kwargs)

def resnet56(**kwargs):
    return ResNet(BasicBlock, [9, 9, 9], num_classes=10, dataset='cifar10', **kwargs)

def resnet110(**kwargs):
    return ResNet(BasicBlock, [18, 18, 18], num_classes=10, dataset='cifar10', **kwargs)
